package com.carlinfo.shop.goods.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.shop.common.service.BaseServiceImpl;
import com.carlinfo.shop.common.util.ConstatFinalUtil;
import com.carlinfo.shop.common.util.PageInfoUtil;
import com.carlinfo.shop.goods.dao.IAGoodsBrandDao;
import com.carlinfo.shop.goods.dao.IAGoodsCateDao;
import com.carlinfo.shop.goods.dao.IAGoodsDao;
import com.carlinfo.shop.goods.dao.IAUsersCarDao;
import com.carlinfo.shop.goods.pojo.AGoods;
import com.carlinfo.shop.goods.pojo.AGoodsBrand;
import com.carlinfo.shop.goods.pojo.AGoodsCate;
import com.carlinfo.shop.goods.pojo.AUsersCar;
import com.carlinfo.shop.goods.service.IGoodsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 商品模块的Service
 * @author wangshMac
 */
@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl implements IGoodsService
{
	@Resource
	private IAGoodsBrandDao goodsBrandDao;
	@Resource
	private IAGoodsDao goodsDao;
	@Resource
	private IAGoodsCateDao goodsCateDao;
	@Resource
	private IAUsersCarDao usersCarDao;
	
	/**
	 * {
			// 响应码
			"code":"0",
			// 响应信息
			"info":"",
			// 数据
			"data":
			{
				// 影响条数;sql执行以后对数据库的影响条数
				"effect":"",
				// id,保存的时候要主键
				"id":""
			}
		}
	 */
	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject() ; 
		/* 保存 */
		int res = this.goodsBrandDao.saveOne(goodsBrand);
		
		/* 抛空指针,就是为了测试事务管理器 */
		/*String str = null ; 
		str.toString() ;*/
		
		if(res > 0 )
		{
			JSONObject dataJSON = new JSONObject() ; 
			dataJSON.put("effect", res);
			dataJSON.put("id", goodsBrand.getId());
			
			resultJSON.put("data", dataJSON);
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject() ; 
		/* 保存 */
		int res = this.goodsBrandDao.updateOne(goodsBrand);
		
		/* 抛空指针,就是为了测试事务管理器 */
		/*String str = null ; 
		str.toString() ;*/
		
		if(res > 0 )
		{
			JSONObject dataJSON = new JSONObject() ; 
			dataJSON.put("effect", res);
			dataJSON.put("id", goodsBrand.getId());
			
			resultJSON.put("data", dataJSON);
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand,Map<String, Object> condMap) throws Exception
	{
		/* 先更新数据库的记录 */
		JSONObject resultJSON = this.updateOneGoodsBrandService(goodsBrand);
		try
		{
			String fileName = (String) condMap.get("fileName");
			InputStream is = (InputStream) condMap.get("inputStream");
			if("0".equalsIgnoreCase(resultJSON.getString("code")))
			{
				if(fileName != null && is != null)
				{
					/* 用户点击了上传文件 */
					/* 拼装三个路径:
					 * 绝对路径:
					 * 相对路径:
					 * 网络路径:在显示的时候使用
					 *  */
					String webpath = ConstatFinalUtil.CONFIG_JSON.getString("path.webpath");
					String website = ConstatFinalUtil.CONFIG_JSON.getString("path.website");
					String rela = ConstatFinalUtil.CONFIG_JSON.getString("path.rela");
					
					/* 拼装相对路径:
					 * /uploadfile/+模块名+日期+uuid.jpg
					 * 
					 * 文件名:1.jpg
					 *  */
					rela = rela + "/good/brand/" + this.dateUtil.dateToStr(new Date()) + "/" + UUID.randomUUID().toString() + 
							fileName.substring(fileName.lastIndexOf("."), fileName.length());
					/* 拼装本地的绝对路径 */
					webpath = webpath + rela ; 
					FileOutputStream fos = new FileOutputStream(new File(webpath));
					
					/* 复制文件 */
					if(!this.fileUtil.copy(is, fos))
					{
						ConstatFinalUtil.LOGGER.error("上传文件失败了;目标文件是:{}",webpath);
					}
					
					goodsBrand.setLogoPath(rela);
					/* 就是为了更新上传文件的路径 */
					this.goodsBrandDao.updateOne(goodsBrand);
				}
				
				/* 成功 */
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				/* 失败 */
				resultJSON.put("code", "1");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			}
		} catch (Exception e)
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			throw e ; 
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsBrandService(Map<String, Object> condMap)
	{
		return null;
	}

	@Override
	public AGoodsBrand findOneGoodsBrandService(Map<String, Object> condMap)
	{
		return this.goodsBrandDao.findOne(condMap);
	}

	@Override
	public Map<String, Object> findCondListGoodsBrandService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 为关键字加上模糊匹配 */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}
			
		if(pageInfoUtil != null)
		{
			/* 分页 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AGoodsBrand> goodsBrandList = this.goodsBrandDao.findList(condMap);
			/* 一定要把总记录数放到pageInfoUtil中 */
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("goodsBrandList", goodsBrandList);
			resultMap.put("totalRecord", Integer.valueOf(page.getTotal() + ""));
		}else
		{
			List<AGoodsBrand> goodsBrandList =  this.goodsBrandDao.findList(condMap);
			resultMap.put("goodsBrandList", goodsBrandList);
		}
		return resultMap ; 
	}

	@Override
	public AGoodsCate findOneGoodsCateService(Map<String, Object> condMap)
	{
		return this.goodsCateDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.saveOne(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.updateOne(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public Map<String, Object> findCondListGoodsCateService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AGoodsCate> roleList = this.goodsCateDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			
			resultMap.put("list", roleList);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			return resultMap;
		}
		/* 不分页查询数据 */
		List list = this.goodsCateDao.findList(condMap);
		resultMap.put("list", list);
		return resultMap ; 
	}
	
	@Override
	public AGoods findOneGoodsService(Map<String, Object> condMap)
	{
		return this.goodsDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsDao.saveOne(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	/**
	 * 保存一条商品
	 * @param goods	保存的对象
	 * @return	json:{"code":"0","info":"成功","data":{"effect":"","id":""}}
	 */
	public JSONObject saveOneGoodsService(AGoods goods,Map<String, Object> paramsMap)
	{
		JSONObject resultJSON = this.saveOneGoodsService(goods);
		return resultJSON ; 
	}
	
	@Override
	public JSONObject updateOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsDao.updateOne(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public Map<String, Object> findCondListGoodsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			/* 分页 */
			/* 查询总记录数 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(),pageInfoUtil.getPageSize());
			List<AGoods> goodsList = this.goodsDao.findList(condMap);
			resultMap.put("list", goodsList);
			
			pageInfoUtil.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
			/* 设置总记录数 */
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			return resultMap ; 
		}
		/* 不分页查询数据 */
		List<AGoods> goodsList = this.goodsDao.findList(condMap);
		resultMap.put("list", goodsList);
		return resultMap ; 
	}
	
	public Map<String, Object> statGoodsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(pageInfoUtil != null)
		{
			/* 分页 */
			/* 查询总记录数 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(),pageInfoUtil.getPageSize());
			/* 查询数据 */
			List<Map<String, Object>> list= this.goodsDao.statDao(condMap);
			resultMap.put("list", list);
			
			pageInfoUtil.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
			/* 设置总记录数 */
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			return resultMap ; 
		}
		/* 不分页查询数据 */
		List<Map<String, Object>> list= this.goodsDao.statDao(condMap);
		resultMap.put("list", list);
		return resultMap ; 
	}

	@Override
	public List<AGoodsCate> findTreeListGoodsCateService()
	{
		List<AGoodsCate> resultList = new ArrayList<AGoodsCate>();
		
		/* 先查询出一级节点 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 按照父节点查询 */
		condMap.put("parentId", "0");
		Map<String, Object> resultMap = this.findCondListGoodsCateService(null, condMap);
		List<AGoodsCate> childList = (List<AGoodsCate>) resultMap.get("list");
		for (Iterator iterator = childList.iterator(); iterator.hasNext();)
		{
			AGoodsCate goodsCate = (AGoodsCate) iterator.next();
			this.findTreeListGoodsCateServiceUtil(resultList , goodsCate,0);
		}
		return resultList;
	}
	
	private void findTreeListGoodsCateServiceUtil(List<AGoodsCate> resultList,AGoodsCate goodsCate,int level)
	{
		StringBuffer sb = new StringBuffer() ; 
		for(int i = 0 ; i < level ; i ++)
		{
			sb.append("|-->");
		}
		//ConstatFinalUtil.LOGGER.info(sb.toString() + goodsCate.getName());
		/* 存储前置字符串 */
		goodsCate.setTreeName(sb.toString() + goodsCate.getName());
		/* 所有的树形节点都存储起来,存储到一个集合中 */
		resultList.add(goodsCate);
		/* 查询子节点
		 * select * from a_goodscate where parentid = id 
		 *  */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("parentId", goodsCate.getId());
		Map<String, Object> resultMap = this.findCondListGoodsCateService(null, condMap);
		List<AGoodsCate> childList = (List<AGoodsCate>) resultMap.get("list");
		
		if(childList.size() == 0)
		{
			/* 木有子节点 */
			goodsCate.setLeafStatus("1");
		}else
		{
			/* 有子节点 */
			goodsCate.setLeafStatus("0");
		}
		
		/* 如果有子节点,就自己调用自己查询子节点
		 * 如果木有子节点,终止不再调用自己 */
		/* 自己调用自己可以出来 
		 * 当前节点找不到子节点的时候就出来(查询出的childList是空的)
		 * */
		for (Iterator iterator = childList.iterator(); iterator.hasNext();)
		{
			AGoodsCate goodsCateTemp = (AGoodsCate) iterator.next();
			this.findTreeListGoodsCateServiceUtil(resultList,goodsCateTemp,level + 1 );
		}
	}
	@Override
	public AUsersCar findOneUsersCarService(Map<String, Object> condMap)
	{
		return this.usersCarDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneUsersCarService(AUsersCar usersCar)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.usersCarDao.saveOne(usersCar);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", usersCar.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneUsersCarService(AUsersCar usersCar)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.usersCarDao.updateOne(usersCar);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", usersCar.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneUsersCarService(AUsersCar usersCar)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.usersCarDao.deleteOne(usersCar);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", usersCar.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}
	
	@Override
	public Map<String, Object> findCondListUsersCarService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String,Object> resultMap = new HashMap<String, Object>();
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage() ,pageInfoUtil.getPageSize());
			List<AUsersCar> roleList = this.usersCarDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			
			resultMap.put("list", roleList);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			return resultMap ; 
		}
		/* 不分页查询数据 */
		List<AUsersCar> roleList = this.usersCarDao.findList(condMap);
		resultMap.put("list", roleList);
		return resultMap ; 
	}
}
